<template>
	<div ref="machineRealTimeChart" v-resize="resizeChart" style="width: 100%;height: 100%;"></div>
</template>

<script>

    import * as echarts from 'echarts';
    import { color, borderColor, legendTextStyle } from './chart-conf';
    import homeMixin from '../../../../../mixins/dom-resize';
    import { reportProductionHomeDataMachineRunStatus } from '../../../../../api/production/kanBan';
    export default {
        name: 'MachineRealTimeChart',
        props: {
            homeData: {
                type: Object,
                default() {
                    return {};
                }
            },
            refreshData: {
                type: [Number, String],
                default: ''
            },
            workshopId: {
                type: Number,
                default: null
            },
            processCode: {
                type: String,
                default: 'XS'
            }
        },
        mixins: [homeMixin],
        data() {
            return {
                timer: {},
                chartData: [],
                example: null,
                borderColor: '#c5c8ce',
                option: {
                    title: {
                        text: '',
                        textStyle: {
                            fontWeight: 'none'
                        }
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter(params) {
                            let str = '';
                            str += `<div style="display: flex; align-items: center;">${params[0].axisValueLabel}</div>`;
                            str += `<div style="display: flex; align-items: center;"><div style="width: 10px;height: 10px;border-radius: 50%;background: #dcdee2;margin-right: 4px;"></div><span>${params[0].seriesName}: ${params[0].value} </span></div>`;
                            str += `<div style="display: flex; align-items: center;"><div style="width: 10px;height: 10px;border-radius: 50%;background: #4AD47A;margin-right: 4px;"></div><span>${params[1].seriesName}: ${params[1].value} </span></div>`;
                            str += `<div style="display: flex; align-items: center;"><div style="width: 10px;height: 10px;border-radius: 50%;background: #ed4014;margin-right: 4px;"></div><span>${params[2].seriesName}: ${params[2].value} </span></div>`;
                            return str;
                        }
                    },
                    grid: {
                        top: '30px',
                        right: '10px',
                        bottom: '10px',
                        left: '20px',
                        containLabel: true
                    },
                    legend: {
                        data: ['今日产量(kg)', '当班产量(kg)', '锭速(r/min)'],
                        textStyle: {
                            color: legendTextStyle
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: [323, 242, 355, 276, 118, 434, 251],
                        axisLabel: {
                            show: true,
                            color: color

                        },
                        nameTextStyle: {
                            color: 'red'
                        },
                        boundaryGap: true,
                        axisLine: {
                            lineStyle: {
                                color: borderColor
                            }
                        }
                    },
                    yAxis: [
                        {
                            type: 'value',
                            name: 'KG',
                            nameLocation: 'end',
                            nameTextStyle: {
                                align: 'right'
                            },
                            splitLine: {
                                lineStyle: {
                                    color: 'none'
                                }
                            },
                            axisLabel: {
                                show: true,
                                color: color

                            },
                            axisLine: {
                                lineStyle: {
                                    color: borderColor
                                }
                            }
                        },
                        {
                            type: 'value',
                            name: 'r/min',
                            nameLocation: 'end',
                            nameTextStyle: {
                                align: 'left'
                            },
                            splitLine: {
                                lineStyle: {
                                    color: 'none'
                                }
                            },
                            axisLabel: {
                                show: true,
                                color: color

                            },
                            axisLine: {
                                lineStyle: {
                                    color: borderColor
                                }
                            }
                        }
                    ],
                    series: [
                        {
                            name: '今日产量(kg)',
                            type: 'bar',
                            data: [],
                            label: {
                                show: true,
                                position: 'outside',
                                borderType: 'none',
                                color: '#808695',
                                textBorderColor: 'none'
                            },
                            smooth: true,
                            barGap: 0,
                            symbol: 'none',
                            itemStyle: {
                                normal: {
                                    color: 'rgba(255, 255, 255, 0.1)',
                                    barBorderColor: '#dcdee2',
                                    borderType: 'solid'
                                }
                            },
                            emphasis: {
                                itemStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: '#2378f7' },
                                        { offset: 0.7, color: '#2378f7' },
                                        { offset: 1, color: '#2378f7' }
                                    ])
                                }
                            }
                        },
                        {
                            name: '当班产量(kg)',
                            type: 'bar',
                            data: [],
                            label: {
                                show: true,
                                position: 'outside',
                                borderType: 'none',
                                color: '#808695',
                                textBorderColor: 'none'
                            },
                            smooth: true,
                            symbol: 'none',
                            barGap: '-100%',
                            itemStyle: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: '#7bf6a5' },
                                    { offset: 0.5, color: '#4AD47A' },
                                    { offset: 1, color: '#4AD47A' }
                                ])
                            },
                            emphasis: {
                                itemStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: '#4AD47A' },
                                        { offset: 0.7, color: '#4AD47A' },
                                        { offset: 1, color: '#4AD47A' }
                                    ])
                                }
                            }
                        },
                        {
                            name: '锭速(r/min)',
                            type: 'line',
                            data: [],
                            yAxisIndex: 1,
                            smooth: true,
                            symbol: 'none',
                            barGap: '-100%',
                            itemStyle: {
                                color: '#ed4014'
                            }
                        }
                    ]
                }
            };
        },
        methods: {
            resize() {
                window.addEventListener('resize', () => {
                    this.resizeChart();
                });
            },
            initChart() {
                this.$nextTick(() => {
                    this.example = echarts.init(this.$refs.machineRealTimeChart);
                    this.example.setOption(this.option);
                });
            },
            updateChart() {
                if (this.example) {
                    this.$nextTick(() => {
                        this.option.xAxis.data = this.chartData.map(x => x.machineName);
                        this.option.series[0].data = this.chartData.map(x => x.totalShiftQty);
                        this.option.series[1].data = this.chartData.map(x => x.shiftQty);
                        this.option.series[2].data = this.chartData.map(x => x.spindleSpeed);
                        this.example.setOption(this.option);
                    });
                } else {
                    this.initChart();
                }
            },
            /**
             * setCurrentPageData 前端分页
             * @param {*} data 源数据
             * @param {*} curPage 当前页
             * @param {*} curPageSize
             * @param {*} total 总页码
             */
            setCurrentPageData(data, curPage, pageSize, total) {
                let dataList = [];
                const begin = curPage * pageSize; // 数组截取开始位置 exp: curPage  = 1， pageSize= 2，则截取位置从下标为2的数据开始截取
                const last = (total - curPage) * pageSize; // exp: 总记录13条时，剩下1条
                if (parseInt(total) === curPage) {
                    if (last > 0) { // 这个判断必须要有，防止最后一页数据刚好等于pageSize，会出现一页空白页
                        dataList = data.slice(begin, begin + last);
                    }
                } else {
                    dataList = data.slice(begin, begin + pageSize);
                }
                return dataList;
            },
            getDataRequest() {
                if (!this.workshopId) return false;
                return reportProductionHomeDataMachineRunStatus({
                    workshopId: this.workshopId,
                    processCode: this.processCode
                }).then(res => {
                    if (res.data.status === 200) {
                        const arr = res.data.res ? res.data.res.map(x => {
                            return x;
                        }) : [];
                        const pageSize = 20;
                        const maxPage = Math.ceil(arr.length / pageSize);
                        let pageIndex = 0;
                        this.chartData = this.setCurrentPageData(arr, pageIndex, pageSize, arr.length);
                        this.updateChart();
                        pageIndex++;
                        clearInterval(this.timer);
                        this.timer = setInterval(() => {
                            if (pageIndex + 1 >= maxPage) {
                                pageIndex = 0;
                            } else {
                                pageIndex++;
                            }
                            this.chartData = this.setCurrentPageData(arr, pageIndex, pageSize, arr.length);
                            this.updateChart();
                        }, 4000);
                    }
                });
            }
        },
        mounted() {
            this.resize();
            this.initChart();
        },
        watch: {
            refreshData: {
                handler(newVal) {
                    this.getDataRequest();
                },
                deep: true,
                immediate: true
            }
        },
        destroyed() {
            clearInterval(this.timer);
        }
    };
</script>

<style scoped lang="scss"></style>
